package com.kevin.concurrent;

/**
 * @author Kevin Liu
 * @date 2020/9/27 4:59 下午
 */
public class First {

    public static final Object resourceA = new Object();

    public static final Object resourceB = new Object();

    public static void main(String[] args) {
        Thread threadA = new Thread(()->{
             synchronized (resourceA) {
                 print("threadA","resourceA","get");
                 synchronized (resourceB) {
                     print("threadA","resourceB","get");
                     try {
                         print("threadA","resourceA","release");
                         resourceA.wait();
                     } catch (InterruptedException e) {
                         e.printStackTrace();
                     }
                 }
             }
        });

        Thread threadB = new Thread(()->{
            try {
                //让A现成先执行
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            synchronized (resourceA) {
                print("threadB","resourceA","get");
                synchronized (resourceB) {
                    print("threadB","resourceB","get");
                    try {
                        print("threadB","resourceA","release");
                        resourceA.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        });
        threadA.start();
        threadB.start();
    }

    private static void print(String tName,String rName,String opt){
        System.out.printf("%s %s the %s",tName,opt,rName);
        System.out.println();
    }
}
